/**
* @author  sparkHou
* @date 2020-11-04 17:23
* @Description:
*/

<template>
  <div class="cmsUploadVideo" :class="disabled?'noneBtn':''">
    <el-upload class="upload-demo " style="display: inline-block" v-loading="isLoading" multiple action :before-upload="(file)=>beforeUpload(file)" :show-file-list="false" :class="{hide: detailType == 'check'||hideAdd}" :disabled="detailType != 'build'&&detailType!='edit'">
      <div class="el-upload el-upload--picture-card">
        <i class="el-icon-plus" v-if="(detailType == 'build'||detailType=='edit')||isShowUploadVideo"></i>
      </div>
    </el-upload>
    <div v-if="detailType == 'build'||detailType=='edit'">
      <i class="el-icon-warning"></i> 最多可以上传5个视频，最大上传为500MB,推荐格式mp4
    </div>
    <div style="display: flex;flex-direction: row; align-items: flex-end;position: relative">
      <div v-for="(item,index) in list" @mouseover="isPopContainer = true;chooseIndex = index" style="width: 148px;height: 148px;background-color: white;z-index: 20;position: relative;margin: 0 5px;">
        <video width="146px;" height="146px" :src="item.url">
          您的浏览器不支持视频播放
        </video>
        <div @mouseout="isPopContainer = false;chooseIndex = null">
          <div v-if="isPopContainer&&chooseIndex == index" class='popContainer' style=" width: 146px;height: 146px;"></div>
          <div v-if="isPopContainer&&chooseIndex == index" class="video-remove el-icon-zoom-in" style="left:46px;color: #ffffff;font-size: 20px" @click="handleVideoPreview(item,index)"></div>
          <div v-if="detailType=='check'&&chooseIndex == index" class="video-remove el-icon-download" style="left:80px;color: #ffffff;font-size: 20px" @click="download(item,index)"></div>
          <div v-if="isPopContainer&&!disabled&&chooseIndex == index" class="video-remove el-icon-delete" style="left:82px;color: #ffffff;font-size: 20px" @click="removeFile_video(item,index)"></div>
        </div>
      </div>
    </div>

    <el-dialog append-to-body v-dialog-drag destroy-on-close :modal-append-to-body="false" :close-on-click-modal="false" :visible.sync="video.show">
      <div oncontextmenu="self.event.returnValue = false" style="max-height: 600px;overflow-y: auto" class="WholeScroll flex-hv-center">
        <video v-if="showVideo" id="video" style="width:600px;height: 500px" controls :src="video.url" controlsList="nodownload">
        </video>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import msgUtil from '@/utils/msgUtil'
import { Base64 } from 'js-base64'
const PREVIEW_URL = process.env.VUE_APP_FILE_PREVIEW
import { v4 as uuidv4 } from 'uuid';
export default {
  name: "cmsUploadVideo",
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    detailType: {
      type: String,
      default: ''
    },
    hideAdd: {
      type: Boolean,
      default: false
    },
    fileList: {
      type: Array,
      default: []
    },
    fileSystem: {
      type: Object,
      default: {
        sys: '',
        module: '',
        entityClass: '',
        viewByAnon: true,
        longLife: false,
      }
    },
    filePart: {
      type: String,
      default: ''
    },
    detailId: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'single'
      //  mul--多文件，single---单文件
    },
    info: {
      type: String,
      default: ''
      //  文件支持类型
    },
    //文件類型校验方法-若需要校验，从父组件传入此方法
    checkFiles: {
      type: Function,
      default: (file) => {
        return true
      }
    },
    //获取文件后的回调函数-从父组件传入此方法
    getFilesCb: {
      type: Function,
      default: () => {
      }
    },
    //获取文件后的回调函数-从父组件传入此方法
    uploadCb: {
      type: Function,
      default: () => {
      }
    }
  },
  watch: {
    'detailId': {
      handler(val) {

        this.isSaveFile = false
        if (this.oldUuid && !val) {
        } else {
          if (val) {
            this.init()
          } else {
            this.$set(this, 'list', [])
          }
        }
      },
      deep: true
    },
    'fileList': {
      handler(val) {
        this.list = [...val]
      },
      deep: true
    },
    'hideAdd': {
      handler(val) {
        console.log(val, 'hideAdd')

      },
      deep: true
    }
  },
  data() {
    return {
      isSaveFile: false,
      oldUuid: null,
      isLoading: false,
      showVideo: true,
      list: [],
      isPopContainer: false,
      chooseIndex: null,
      videoFlag: false,
      //是否显示进度条
      videoUploadPercent: "",
      //进度条的进度，
      isShowUploadVideo: false,
      video: {
        show: false,
        url: ''
      },
    }
  },
  created() {

  },
  methods: {
    async saveAll(formId) {

      console.log(this.list, 'list')
      this.detailId = formId
      this.isSaveFile = true
      let queue = []
      this.list.forEach(it => {
        queue.push(this.beforeUpload(it.file, this.fileSystem.part))
      })
      this.list = []
      const res = await Promise.all(queue)
      console.log(res)
      return res
    },
    init() {

      if (!this.detailId) {
        this.oldUuid = this.uuid()
        return
      }


      this.$publicUpload.getFile(this.fileSystem.module, this.detailId, this.fileSystem.part)
        .then(res => {
          const items = res.data || []
          const arr = []
          items.forEach(o => {
            arr.push({
              realName: o.name,
              name: o.name,
              size: o.size,
              id: o.id,
              url: `${process.env.VUE_APP_BASE_API}/file-server/file/download?id=` + o.id,
            })
          })
          this.list = arr
          this.change()
        })
    },
    uploadPartOne(file, part, fileList) {
      this.beforeUpload(file, part, fileList)
    },
    // 上传文件前
    async beforeUpload(file) {
      var fileSize = file.size / 1024 / 1024 < 500;
      if (['video/mp4'].indexOf(file
        .type) == -1) {
        msgUtil.error2("请上传正确的mp4视频格式");
        return false;
      }
      if (this.list.length >= 5) {
        msgUtil.error2("只能上传5个视频");
        return false;
      }
      if (!fileSize) {
        msgUtil.error2("视频大小不能超过500MB");
        return false;
      }
      this.isShowUploadVideo = false;
      /*
      *公共上传方法
      * */

      this.$set(this, 'isLoading', true)
      let form = this.detailId
      if (!this.detailId) {
        form = this.oldUuid
      }
      if (!this.isSaveFile) {
        form = this.uuid()
      }
      let fd = new FormData()
      fd.append('file', file)
      const response = await this.$publicUpload.uploadFile(
        file,
        form,
        this.fileSystem.module,
        this.fileSystem.part,
        file.name,
      )
        .then(async res => {

          if (res.code === 200) {
            if (this.type === 'single') {
              if (this.list.length != 0) {
                //先解绑
                await this.$publicUpload.removeFile(this.list[0].id)
                this.list = [{
                  file: file,
                  realName: file.name,
                  name: file.name,
                  size: file.size,
                  url: `${process.env.VUE_APP_BASE_API}/file-server/file/download?id=` + res.data[0],
                  id: res.data[0],
                }]
              } else {
                this.list = [{
                  file: file,
                  realName: file.name,
                  name: file.name,
                  size: file.size,
                  url: `${process.env.VUE_APP_BASE_API}/file-server/file/download?id=` + res.data[0],
                  id: res.data[0],
                }]
              }
            }
            if (this.type === 'mul') {
              this.list.push({
                file: file,
                realName: file.name,
                name: file.name,
                size: file.size,
                url: `${process.env.VUE_APP_BASE_API}/file-server/file/download?id=` + res.data[0],
                id: res.data[0],
              })
            }
            this.uploadCb(res)
            console.log(this.list, 'xxxxxxxxxxxxx')
          } else {
            msgUtil.error2(res.data.message)
          }
        })
        .catch(res => {
          console.log(res, '======')
          msgUtil.error2(this.$route.name + '上传文件前-请求失败')
        })
      this.$set(this, 'isLoading', false)
      this.change()
      return response

    },
    getPreviewUrl(id) {
      this.$httpGet('/file-server/file/preview?id=' + id).then(url => {
        return url.data
      })
    },
    // 删除文件时解绑文件
    removeFile(file, fileList, part) {
      let isNew = false
      this.list.forEach((item, index) => {
        if (file.uid === item.uid) {
          this.list.splice(index, 1)
          isNew = true
        }
      })
      if (isNew) {
        this.change()
        return
      }

      if (this.type === 'mul') {
        this.list.forEach((item, index) => {
          if (file.uid === item.uid) {
            this.list.splice(index, 1)
          }
        })
      }
      if (this.type === 'single') {
        this.$set(this, 'list', [])
      }
      //this.$publicUpload.removeFile(file.id)
      this.$publicUpload.removeFile(file.id)
      this.change()
    },
    download(item, index) {
      this.$publicUpload.checkFile(item.id, item.realName)
    },
    change() {
      this.$emit('change', this.list)
    },
    uuid() {
      return uuidv4().split('-')[0]
    },
    handleVideoPreview(item, index) {
      this.showVideo = false
      this.showVideo = true
      this.$set(this.video, 'url', item.url)
      this.video.show = true
      console.log($)
      $('#video').bind('contextmenu', function () { return false; });
    },
    downLoadVideo() {
    },
    removeFile_video(item, index) {
      this.$publicUpload.removeFile(item.id)
      this.list.splice(index, 1)
      this.change()
    },
  }
}
</script>

<style scoped lang="scss">
.cmsUploadVideo {
  width: 400px;

  .fileList {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .fileName {
      display: flex;
      align-items: center;
      cursor: pointer;
    }
  }

  .popContainer {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
  }

  .video-remove {
    position: absolute;
    top: 40%;
    z-index: 999;
    cursor: pointer;
  }
}
.flex-hv-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
<style lang="scss">
.noneBtn {
  .small-payment-upload {
    display: none;
  }
}
.video-box-view {
  max-height: 600px;
}
</style>
